package com.szb.endpoint;

import com.google.gson.Gson;
import com.szb.entity.QueryMessage;
import com.szb.enums.OPERATION;
import com.szb.service.DockerLogsService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.ServerEndpoint;

@Component
@ServerEndpoint("/realtime")
public class DockerLogsWebSocketEndpoint {

    private DockerLogsService dockerLogsService;

    private static ApplicationContext context;

    // 实现ApplicationContextAware接口以获取ApplicationContext的引用
    @Component
    private static class ApplicationContextProvider implements ApplicationContextAware {
        @Override
        public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
            context = applicationContext;
        }
    }

    @OnOpen
    public void onOpen(Session session) {
        String sessionId = session.getId();
        WebSocketSessionManager.addSession(sessionId, session);
        System.out.println("WebSocket 当前连接数：" + WebSocketSessionManager.countSessionNumber());
        this.dockerLogsService = context.getBean(DockerLogsService.class);
    }

    @OnClose
    public void onClose(Session session) {
        String sessionId = session.getId();
        WebSocketSessionManager.removeSession(sessionId);
        System.out.println("WebSocket 当前连接数：" + WebSocketSessionManager.countSessionNumber());
    }



    @OnMessage
    public void onMessage(String message, Session session) {
        Gson gson = new Gson();
        QueryMessage queryMessage = gson.fromJson(message, QueryMessage.class);
        System.out.println("接收到 WebSocket 客户端"+session.getId()+"发来的消息：" + message);
        String containerId = queryMessage.getContainerId();
        String sessionId = session.getId();
        if(queryMessage.getOperation().equals(OPERATION.SUBSCRIBE)){
            dockerLogsService.startLogging(containerId,sessionId);
        }else{
            dockerLogsService.stopLogging(containerId);
        }

    }

}